package com.example.exodemo.lrc;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class DefaultLrcParser {
    private static final DefaultLrcParser instance = new DefaultLrcParser();
    private static final Pattern TIME_TAG_PATTERN = Pattern.compile("\\[(\\d{2}):(\\d{2})\\.(\\d{2,3})\\]");
    private static final Pattern LENGTH_PATTERN = Pattern.compile("\\[length:\\s*(\\d{2}):(\\d{2})\\.(\\d{2,3})\\]");
    private long totalTime = 0;

    private DefaultLrcParser() {}

    public static DefaultLrcParser getInstance() {
        return instance;
    }

    public List<LrcRow> getLrcRows(String lrcContent) {
        if (lrcContent == null || lrcContent.isEmpty()) {
            return null;
        }

        // 解析总时长
        parseTotalTime(lrcContent);

        List<LrcRow> lrcRows = new ArrayList<>();
        String[] lines = lrcContent.split("\\n");

        for (String line : lines) {
            Matcher matcher = TIME_TAG_PATTERN.matcher(line);
            String lyric = line;

            while (matcher.find()) {
                long time = parseTime(matcher.group(1), matcher.group(2), matcher.group(3));
                lyric = lyric.replace(matcher.group(), "");
                lrcRows.add(new LrcRow(time, lyric.trim(), totalTime));
            }
        }

        return lrcRows.isEmpty() ? null : lrcRows;
    }

    private void parseTotalTime(String lrcContent) {
        Matcher matcher = LENGTH_PATTERN.matcher(lrcContent);
        if (matcher.find()) {
            totalTime = parseTime(matcher.group(1), matcher.group(2), matcher.group(3));
        }
    }

    private long parseTime(String minutes, String seconds, String millis) {
        long min = Long.parseLong(minutes);
        long sec = Long.parseLong(seconds);
        long ms = Long.parseLong(millis);

        if (millis.length() == 2) {
            ms *= 10;
        }

        return (min * 60 + sec) * 1000 + ms;
    }
}
